package com.hx.zhg.web.filter;


import com.hx.zhg.constant.CommonConstant;
import com.hx.zhg.constant.ContentType;
import com.hx.zhg.util.DateUtilExt;
import com.hx.zhg.web.factory.ThreadLocalFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * 将request和response信息放入threadlocal
 */
public class ThreadLocalFilter extends BaseFilter {

    // 静态资源缓存时间
    private static final int MAX_AGE = 60 * 60 * 24 * 30; // 缓存30天
    // 静态资源版本号
    private static final String RES_VERSION = DateUtilExt.formatDate(new Date(), DateUtilExt.Format.YYYYMMDDHH);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        //设置CDN 访问路径
        if (cdnUrl == null) {
            cdnUrl = "";
        }
        if (resEnv == null) {
            resEnv = "";
        }

        req.setAttribute("contextPath", contextPath);
        req.setAttribute("cdnUrl", cdnUrl);
        req.setAttribute("resEnv", resEnv);
        req.setAttribute("resVersion", RES_VERSION);    // js等静态资源的版本号
        req.setAttribute(CommonConstant.ENV_KEY, env);    // js等静态资源的版本号

        // 将request对象和response对应存入本地线程
        ThreadLocalFactory.getRequestThreadlocal().set(req);
        ThreadLocalFactory.getResponseThreadlocal().set(res);

        // 得到相对路径 URI,URL会得到全部路径
        String requestURI = req.getRequestURI();
        boolean isStaticFile = this.isStaticFile(requestURI, staticSuffix);
        //设置用户浏览器对静态文件缓存
        if (isStaticFile) {
            res.addHeader("Cache-Control", "max-age=" + MAX_AGE);
        } else { // 对于非静态文件无缓存
            res.addHeader("Cache-Control", "no-cache");
            res.addHeader("Expires", "-1");
        }
        res.setContentType(ContentType.TEXT_HTML);
        chain.doFilter(request, response);

        //从本地线程中移除request和response对象
        ThreadLocalFactory.getRequestThreadlocal().remove();
        ThreadLocalFactory.getResponseThreadlocal().remove();
    }

}
